import java.sql.*;
import java.util.Scanner;

public class JDBCReg {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        System.out.println("请输入用户名:");
        String username=sc.nextLine();
        System.out.println("请输入密码:");
        String password =sc.nextLine();
        System.out.println("昵称:");
        String nickname =sc.nextLine();
        System.out.println("年龄:");
        int age=sc.nextInt();
        try (final Connection connection = DBUtil.getConnection();){
            // 判断用户是否存在
            String sql2="select username from userinfo where username=?";
            final PreparedStatement preparedStatement1 = connection.prepareStatement(sql2);
            preparedStatement1.setString(1,username);
            final ResultSet resultSet = preparedStatement1.executeQuery();
            if (resultSet.next()){
                System.out.println("用户已存在,注册失败");
                return;
            }
            // 执行插入语句
            String sql="INSERT INTO userinfo(username,password,nickname,age) VALUES(?,?,?,?)";
            final PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1,username);
            preparedStatement.setString(2,password);
            preparedStatement.setString(3,nickname);
            preparedStatement.setInt(4,age);
            final int i = preparedStatement.executeUpdate();
            if (i>0){
                System.out.println("注册成功");
            }else {
                System.out.println("注册失败");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
